package com.ruoyi.system.service.impl;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.JsonKV;
import com.ruoyi.system.entity.SysDuty;
import com.ruoyi.system.entity.SysDutyUser;
import com.ruoyi.system.entity.SysRemind;
import com.ruoyi.system.mapper.SysDutyMapper;
import com.ruoyi.system.service.PreventionDeviceService;
import com.ruoyi.system.service.SysDutyService;
import com.ruoyi.system.service.SysDutyUserService;
import com.ruoyi.system.service.SysRemindService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 履职表(SysDuty)表服务实现类
 *
 * @author makejava
 * @since 2022-11-15 14:08:16
 */
@Service("sysDutyService")
public class SysDutyServiceImpl implements SysDutyService {
    @Resource
    private SysDutyMapper sysDutyDao;

    @Resource
    private SysDutyUserService sysDutyUserService;

    @Resource
    private PreventionDeviceService preventionDeviceService;

    @Resource
    private SysRemindService sysRemindService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SysDuty queryById(Integer id) {
        return this.sysDutyDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param sysDuty 筛选条件
     * @return 查询结果
     */
    @Override
    public List<SysDuty> queryByPage(SysDuty sysDuty) {
        if (!SecurityUtils.getUsername().equals("admin")) {
            SysDutyUser sysDutyUser = sysDutyUserService.getByUserId(SecurityUtils.getUserId());
            if (sysDutyUser != null) {
                sysDuty.setDutyType(sysDutyUser.getDutyType());
            } else {
                return new ArrayList<>();
            }
        }
        List<SysDuty> sysDuties = sysDutyDao.queryAllByLimit(sysDuty);
        sysDuties.forEach(i -> {
            if (i.getDutyType().equals("技术负责人")) {
                String dutyData = i.getDutyData();
                JSONObject jsonObject = new JSONObject(dutyData);
                String data = preventionDeviceService.getAllCountByDangerName(i.getDangerName(),i.getDutyInfoName(),i.getDutyType());
                JsonKV jsonKV = new JsonKV();
                jsonKV.setKey(data);
                jsonKV.setValue(DateUtil.now());
                jsonObject.set("隐患排除与治理情况",JSONUtil.toJsonStr(jsonKV));
                i.setDutyData(JSONUtil.toJsonStr(jsonObject));
            } else
            if (i.getDutyType().equals("操作负责人")) {
                //             map.put("重大危险源安全风险隐患排查","");
                //            map.put("重大危险源隐患治理","");
                String dutyData = i.getDutyData();
                JSONObject jsonObject = new JSONObject(dutyData);
                String data = preventionDeviceService.getAllCountByDangerName(i.getDangerName(),i.getDutyInfoName(),i.getDutyType());
                String[] split = data.split(";");
                JsonKV jsonKV = new JsonKV();
                jsonKV.setKey(split[0]);
                jsonKV.setValue(DateUtil.now());
                jsonObject.set("重大危险源安全风险隐患排查",JSONUtil.toJsonStr(jsonKV));
                JsonKV jsonKVs = new JsonKV();
                jsonKVs.setKey(split[1]);
                jsonKVs.setValue(DateUtil.now());
                jsonObject.set("重大危险源隐患治理",JSONUtil.toJsonStr(jsonKVs));
                i.setDutyData(JSONUtil.toJsonStr(jsonObject));
            }
        });
        return sysDuties;
    }


    /*  @Override
    public List<SysDuty> queryByPage(SysDuty sysDuty) {
        if (!SecurityUtils.getUsername().equals("admin")) {
            SysDutyUser sysDutyUser = sysDutyUserService.getByUserId(SecurityUtils.getUserId());
            if (sysDutyUser != null) {
                sysDuty.setDutyType(sysDutyUser.getDutyType());
            } else {
                return new ArrayList<>();
            }
        }
        List<SysDuty> sysDuties = sysDutyDao.queryAllByLimit(sysDuty);
        sysDuties.forEach(i -> {
            if (i.getDutyType().equals("技术负责人")) {
                String dutyData = i.getDutyData();
                JSONObject jsonObject = new JSONObject(dutyData);
                String data = preventionDeviceService.getAllCountByDangerName(i.getDangerName(),i.getDutyInfoName(),i.getDutyType());
                Object s = jsonObject.get("隐患排除与治理情况");
                JSONArray objects = new JSONArray(s);
                String time = (String)objects.get(1);
                objects.clear();
                objects.add(data);
                objects.add(time);
                jsonObject.set("隐患排除与治理情况",JSONUtil.toJsonStr(objects));
                i.setDutyData(JSONUtil.toJsonStr(jsonObject));
            } else
            if (i.getDutyType().equals("操作负责人")) {
                //             map.put("重大危险源安全风险隐患排查","");
                //            map.put("重大危险源隐患治理","");
                String dutyData = i.getDutyData();
                JSONObject jsonObject = new JSONObject(dutyData);
                String data = preventionDeviceService.getAllCountByDangerName(i.getDangerName(),i.getDutyInfoName(),i.getDutyType());
                String[] split = data.split(";");
                jsonObject.set("重大危险源安全风险隐患排查",split[0]);
                jsonObject.set("重大危险源隐患治理",split[1]);
                i.setDutyData(JSONUtil.toJsonStr(jsonObject));
            }
        });
        return sysDuties;
    }*/


    /**
     * 新增数据
     *
     * @param sysDuty 实例对象
     * @return 实例对象
     */
    @Override
    public SysDuty insert(SysDuty sysDuty) {
        sysDuty.setWhetherDelete(checkDutyStatus(sysDuty));
        this.sysDutyDao.insert(sysDuty);
        SysDutyUser sysDutyUser = sysDutyUserService.getByDutyType(sysDuty.getDutyType());
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("请尽快完成");
        stringBuffer.append(sysDuty.getDangerName());
        stringBuffer.append("-");
        stringBuffer.append(sysDuty.getDutyInfoName());
        stringBuffer.append("履职任务");
        sysRemindService.insert(SysRemind.TYPE_PROMPT,stringBuffer.toString(),sysDutyUser.getUserId());
        return sysDuty;
    }

    /**
     * 修改数据
     *
     * @param sysDuty 实例对象
     * @return 实例对象
     */
    @Override
    public SysDuty update(SysDuty sysDuty) {
        sysDuty.setWhetherDelete(checkDutyStatus(sysDuty));
        this.sysDutyDao.update(sysDuty);
        return this.queryById(sysDuty.getId());
    }

    public String checkDutyStatus(SysDuty sysDuty) {
        String dutyData = sysDuty.getDutyData();
        JSONObject jsonObject = JSONUtil.parseObj(dutyData);
        Set<String> set = jsonObject.keySet();
        Boolean comp = true;
        for (String s : set) {
            if (s.equals("重大危险源隐患治理")) {
                continue;
            }
            if (s.equals("隐患排除与治理情况")) {
                String yh = jsonObject.getStr("隐患排除与治理情况");
                String str = yh.split("二")[0];
                if (str.contains("0")) {
                    comp = false;
                }
            }
            if (s.equals("重大危险源安全风险隐患排查")) {
                String zd = jsonObject.getStr("重大危险源安全风险隐患排查");
                String str = zd.split("二")[0];
                if (str.contains("0")) {
                    comp = false;
                }
            }
            String str = jsonObject.getStr(s);
            if (StrUtil.isEmpty(str)) {
                comp = false;
                break;
            }
        }
        if (comp) {
            return "已完成";
        }else {
            return "未完成";
        }
    }

    /*    public String checkDutyStatus(SysDuty sysDuty) {
        String dutyData = sysDuty.getDutyData();
        JSONObject jsonObject = JSONUtil.parseObj(dutyData);
        Set<String> set = jsonObject.keySet();
        Boolean comp = true;
        for (String s : set) {
            if (s.equals("重大危险源隐患治理")) {
                continue;
            }
            if (s.equals("隐患排除与治理情况")) {
                String yh = jsonObject.getStr("隐患排除与治理情况");
                String str = yh.split("二")[0];
                if (str.contains("0")) {
                    comp = false;
                }
            }
            if (s.equals("重大危险源安全风险隐患排查")) {
                String zd = jsonObject.getStr("重大危险源安全风险隐患排查");
                String str = zd.split("二")[0];
                if (str.contains("0")) {
                    comp = false;
                }
            }
            String str = jsonObject.getStr(s);
            if (StrUtil.isEmpty(str)) {
                comp = false;
                break;
            }
        }
        if (comp) {
            return "已完成";
        }else {
            return "未完成";
        }
    }
*/

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.sysDutyDao.deleteById(id) > 0;
    }


    @Scheduled(cron = "0 0 0 1/1 * ? ")
    public void checkDutyState() {
        List<SysDuty> sysDuties = sysDutyDao.queryAllByLimit(new SysDuty());
        sysDuties.forEach(i -> {
            if (i.getWhetherDelete().equals("未完成")) {
                // 获取结束时间---判断是否超期
                String dutyInfoName = i.getDutyInfoName();
                String dutyType = i.getDutyType();
                String endTime = "";
                if (dutyType.equals("技术负责人")) {
                    String year = StrUtil.sub(dutyInfoName, 0, 4);
                    String quarter = StrUtil.sub(dutyInfoName, 6, 7);
                    endTime = PreventionDeviceServiceImpl.getEndTime(quarter, year);
                } else if (dutyType.equals("操作负责人")) {
                    String year = StrUtil.sub(dutyInfoName, 0, 4);
                    String week = StrUtil.sub(dutyInfoName, 6, 7);
                    String weeks = StrUtil.sub(dutyInfoName, 7, 8);
                    if (!weeks.equals("周")) {
                        week = week + weeks;
                    }
                    String[] strings = PreventionDeviceServiceImpl.weekToDayFormate(Integer.valueOf(year), Integer.valueOf(week));
                    endTime = strings[1];
                } else {
                    String year = StrUtil.sub(dutyInfoName, 0, 4);
                    String quarter = StrUtil.sub(dutyInfoName, 5, 6);
                    if (quarter.equals("上")) {
                        endTime = "-06-01 00:00:00";
                    } else {
                        endTime = "-01-01 00:00:00";
                    }
                }
                DateTime parse = DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss");
                Date date = parse.toJdkDate();
                DateTime now = DateUtil.date();
                boolean after = date.after(now);
                // 超期
                if (!after) {
                    i.setWhetherDelete("超期");
                    sysDutyDao.update(i);
                    SysDutyUser sysDutyUser = sysDutyUserService.getByDutyType(i.getDutyType());
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append("您的履职任务");
                    stringBuffer.append(i.getDangerName());
                    stringBuffer.append("-");
                    stringBuffer.append(i.getDutyInfoName());
                    stringBuffer.append("已超期");
                    sysRemindService.insert(SysRemind.TYPE_PROMPT,stringBuffer.toString(),sysDutyUser.getUserId());
                }
            }
        });
    }

}


